//
//  notitestVC.m
//  UIScrollView的快速使用
//
//  Created by hongfei tam on 2019/3/15.
//  Copyright © 2019 YQ05. All rights reserved.
//

#import "notitestVC.h"

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif

#define LocalNotiReqIdentifer    @"LocalNotiReqIdentifer"

@interface notitestVC ()

@end

@implementation notitestVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setTitle:@"notitestVC"];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    CGSize size = self.view.frame.size;
    CGFloat offset = 150;
    NSArray *titles = @[@"发送一个本地通知", @"移除一个本地通知"];
    for (int i=0; i<titles.count; i++) {
        NSString *title = [titles objectAtIndex:i];
        UIButton *btn = [self createCustomButton:title];
        btn.tag = i;
        [self.view addSubview:btn];
        btn.center = CGPointMake(size.width/2, offset);
        offset += btn.frame.size.height+10;
    }
    
    //NSString转NSDate
    
    NSString *str = @"2018-04-16";
    NSDateFormatter *df1 = [[NSDateFormatter alloc] init];
    [df1 setDateFormat:@"yyyy-MM-dd"];
    NSLog(@"time : %@", [df1 dateFromString:str]);
    
    //        NSString* string = @"20110826134106";
    //        NSDateFormatter *inputFormatter = [[[NSDateFormatter alloc] init] autorelease];
    //
    //            [inputFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
    //
    //            [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];
    //
    //            NSDate* inputDate = [inputFormatter dateFromString:string];
    //
    //            NSLog(@"date = %@", inputDate);
    //
    //
    //
    //            NSDateFormatter *outputFormatter = [[[NSDateFormatter alloc] init] autorelease];
    //
    //            [outputFormatter setLocale:[NSLocale currentLocale]];
    //
    //            [outputFormatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"];
    //
    //            NSString *str = [outputFormatter stringFromDate:inputDate];
    //
    //            NSLog(@"testDate:%@", str);
    
    
    // NSString *str=@"20120403000000";
    //NSString *timestr = @"20120403000000";
    
//    NSString *datastr =[NSString stringWithFormat:@"有效期至：%@年%@月%@日", [timestr substringWithRange:NSMakeRange(0,4)], [timestr substringWithRange:NSMakeRange(4,2)], [timestr substringWithRange:NSMakeRange(6,2)]];
    
    NSString *timestr = @"2018-04-16";
    NSString *datastr =[NSString stringWithFormat:@"%@年", [timestr substringWithRange:NSMakeRange(0,4)]];
    NSString *datastr2 =[NSString stringWithFormat:@"%@年", [timestr substringWithRange:NSMakeRange(5,2)]];
    NSString *datastr3 =[NSString stringWithFormat:@"%@年", [timestr substringWithRange:NSMakeRange(8,2)]];
    NSLog(@"datastr : %@",datastr );
    NSLog(@"datastr2 : %@",datastr2 );
    NSLog(@"datastr3 : %@",datastr3 );
    //        这个方法笨，可是没办法，查了好多资料，都没明白，今天突然明白了，呵呵，只要把那个[inputFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss Z"];@“”里面的格式转化为你字符串的格式一切就OK了，不知道我说明白了吗
    //
    //        3、iOS-NSDateFormatter 格式说明：
    //
    //
    //
    //    G: 公元时代，例如AD公元
    //
    //            yy: 年的后2位
    //
    //            yyyy: 完整年
    //
    //            MM: 月，显示为1-12
    //
    //            MMM: 月，显示为英文月份简写,如 Jan
    //
    //            MMMM: 月，显示为英文月份全称，如 Janualy
    //
    //            dd: 日，2位数表示，如02
    //
    //            d: 日，1-2位显示，如 2
    //
    //            EEE: 简写星期几，如Sun
    //
    //            EEEE: 全写星期几，如Sunday
    //
    //            aa: 上下午，AM/PM
    //
    //            H: 时，24小时制，0-23
    //
    //            K：时，12小时制，0-11
    //
    //            m: 分，1-2位
    //
    //            mm: 分，2位
    //
    //            s: 秒，1-2位
    //
    //            ss: 秒，2位
    //
    //            S: 毫秒
    //
    //
    //        常用日期结构：
    //
    //        yyyy-MM-dd HH:mm:ss.SSS
    //
    //        yyyy-MM-dd HH:mm:ss
    //
    //        yyyy-MM-dd
    //
    //        MM dd yyyy
    //        ---------------------
    //        作者：51ios
    //        来源：CSDN
    //        原文：https://blog.csdn.net/l_ch_g/article/details/8217725
    //        版权声明：本文为博主原创文章，转载请附上博文链接！
    
    
    //NSCalendar和NSDateComponents使用
    //        NSCalendar *car = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    //        NSDate *date3 = [NSDate date];
    //        unsigned unit = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit;
    //
    //        NSDateComponents *comp = [car components:unit fromDate:date3];
    //        NSLog(@"现在是%ld年", comp.year);
    //        NSLog(@"现在是%ld月", comp.month);
    //        NSLog(@"现在是%ld日", comp.day);
    //        NSLog(@"现在是%ld时", comp.hour);
    //        NSLog(@"现在是%ld分", comp.minute);
    //        NSLog(@"现在是%ld秒", comp.second);

    // Do any additional setup after loading the view.
}

- (UIButton *)createCustomButton:(NSString *)title {
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(0, 0, self.view.frame.size.width-30, 45);
    [btn setTitle:title forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btn.layer setBorderColor:[[UIColor lightGrayColor] colorWithAlphaComponent:0.5].CGColor];
    [btn.layer setBorderWidth:1.0];
    [btn.layer setCornerRadius:5.0];
    [btn.layer setMasksToBounds:YES];
    return btn;
}

- (void)btnClicked:(UIButton *)button {
    if (button.tag == 0) {
        [self sendLocalNotification];
    } else if (button.tag == 1) {
        [self cancelLocalNotificaitons];
    }
}

#pragma mark - 发送一条本地推送通知
- (void)sendLocalNotification {
    
    NSString *title = @"通知-title";
    NSString *subTitle = @"通知-subtitle";
    NSString *body = @"通知-body";
    NSInteger badge = 1;
    NSInteger timeInteval = 5;
    NSDictionary *userInfo = @{@"id":@"LOCAL_NOTIFY_SCHEDULE_ID",@"notiIndex":@12};
    
    /**时间设置 */
    NSString *day = @"2019-04-16";
    NSString *year =[NSString stringWithFormat:@"%@", [day substringWithRange:NSMakeRange(0,4)]];
    NSString *month =[NSString stringWithFormat:@"%@", [day substringWithRange:NSMakeRange(5,2)]];
    NSString *days =[NSString stringWithFormat:@"%@", [day substringWithRange:NSMakeRange(8,2)]];
    NSLog(@"datastr : %@",year );
    NSLog(@"datastr2 : %@",month );
    NSLog(@"datastr3 : %@",days );
    
    NSString *time = @"15:35:00";
    NSString *hours =[NSString stringWithFormat:@"%@", [time substringWithRange:NSMakeRange(0,2)]];
    NSString *minute =[NSString stringWithFormat:@"%@", [time substringWithRange:NSMakeRange(3,2)]];
    NSString *second =[NSString stringWithFormat:@"%@", [time substringWithRange:NSMakeRange(6,2)]];
    NSLog(@"hours : %@",hours );
    NSLog(@"minute : %@",minute );
    NSLog(@"second : %@",second );
    
    /* 时间设置 */
    
    if (@available(iOS 10.0, *)) {
        // 1.创建通知内容
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        //[content setValue:@(YES) forKeyPath:@"shouldAlwaysAlertWhileAppIsForeground"];
        content.sound = [UNNotificationSound defaultSound];
        content.title = title;
        content.subtitle = subTitle;
        content.body = body;
        content.badge = @(badge);
        
        content.userInfo = userInfo;
        
        // 2.设置通知附件内容
//        NSError *error = nil;
//        //NSString *path = [[NSBundle mainBundle] pathForResource:@"faphone_BROWN" ofType:@"png"];
//        //UNNotificationAttachment *att = [UNNotificationAttachment attachmentWithIdentifier:@"att1" URL:[NSURL fileURLWithPath:path] options:nil error:&error];
//        if (error) {
//            NSLog(@"attachment error %@", error);
//        }
        //content.attachments = @[att];
        content.launchImageName = @"banner_b_1500x420-1-1024x287.jpg";
        // 2.设置声音
        UNNotificationSound *sound = [UNNotificationSound defaultSound]; // [UNNotificationSound soundNamed:@"sound01.wav"];// [UNNotificationSound defaultSound];
        content.sound = sound;
        
       
        
        /*重点开始*/
        
         //3.触发模式 延时
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:timeInteval repeats:NO];
         //4.设置UNNotificationRequest
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:LocalNotiReqIdentifer content:content trigger:trigger];
        
        // 3.触发模式 定式
//        NSDateComponents *components = [[NSDateComponents alloc] init];
//        //components.weekday = 4; //周三
//        components.year = year.integerValue;
//        components.month = month.integerValue;
//        components.day = days.integerValue;
//
//        components.hour = hours.integerValue; //13点
//        components.minute = minute.integerValue;
//        components.second = second.integerValue;
        
       
//        UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];
//        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:LocalNotiReqIdentifer content:content trigger:trigger];
        
//        //这个点，100米范围内，进入触发。
//        CLLocationCoordinate2D cen = CLLocationCoordinate2DMake(39.990465,116.333386);
//        CLRegion *region = [[CLCircularRegion alloc] initWithCenter:cen radius:100 identifier:@"center"];
//        region.notifyOnEntry = YES;
//        region.notifyOnExit = NO;
//        UNLocationNotificationTrigger *trigger = [UNLocationNotificationTrigger triggerWithRegion:region repeats:YES];
        /*重点结束*/
        
        
        //5.把通知加到UNUserNotificationCenter, 到指定触发点会被触发
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            NSLog(@"5.把通知加到UNUserNotificationCenter, 到指定触发点会被触发");
        }];
        
    } else {
        
        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
        
        // 1.设置触发时间（如果要立即触发，无需设置）
       localNotification.timeZone = [NSTimeZone defaultTimeZone];
//        localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
        localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];// 5 秒之后
        
        // 2.设置通知标题
        localNotification.alertBody = title;
        
        // 3.设置通知动作按钮的标题
        localNotification.alertAction = @"查看";
        
        // 4.设置提醒的声音
        localNotification.soundName = UILocalNotificationDefaultSoundName;// @"sound01.wav";// UILocalNotificationDefaultSoundName;
        
        // 5.设置通知的 传递的userInfo
        localNotification.userInfo = userInfo;
        
        // 6.在规定的日期触发通知
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
        // 6.立即触发一个通知
        //[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
    }
}

- (void)cancelLocalNotificaitons {
    
    //! 取消一个特定的通知
    NSArray *notificaitons = [[UIApplication sharedApplication] scheduledLocalNotifications];
    //获取当前所有的本地通知
    if (!notificaitons || notificaitons.count <= 0) { return; }
    for (UILocalNotification *notify in notificaitons) {
        if ([[notify.userInfo objectForKey:@"id"] isEqualToString:@"LOCAL_NOTIFY_SCHEDULE_ID"]) {
            if (@available(iOS 10.0, *)) {
                [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[LocalNotiReqIdentifer]];
            } else {
                [[UIApplication sharedApplication] cancelLocalNotification:notify];
            }
            break;
        }
    }
    //! 取消所有的本地通知
    //[[UIApplication sharedApplication] cancelAllLocalNotifications];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
